<?php
// application/api/controller/System.php

namespace app\api\controller;

use app\common\model\Help;
use think\Controller;
use think\Request;
use think\facade\Validate;
use app\api\model\BusinessSystem;

class System extends Controller
{
    protected $model;

    protected function initialize()
    {
        $this->model = new BusinessSystem();
    }

    /**
     * 获取系统列表（分页）
     */
    public function index(Request $request)
    {
        try {
            $page = $request->param('page', 1, 'intval');
            $limit = $request->param('limit', 10, 'intval');
            $sortField = $request->param('sortField', 'sort');
            $sortOrder = $request->param('sortOrder', 'asc');

            // 构建查询条件
            $where = [];

            // 显示状态筛选
            if ($request->has('displayStatus') && $request->param('displayStatus') !== '') {
                $where[] = ['display_status', '=', $request->param('displayStatus')];
            }

            // 系统标签筛选
            if ($request->has('systemTag') && $request->param('systemTag') !== '') {
                $where[] = ['system_tag', '=', $request->param('systemTag')];
            }

            // 系统名称模糊搜索
            if ($request->has('systemName') && $request->param('systemName') !== '') {
                $where[] = ['system_name', 'like', '%' . $request->param('systemName') . '%'];
            }

            // 系统编码模糊搜索
            if ($request->has('systemCode') && $request->param('systemCode') !== '') {
                $where[] = ['system_code', 'like', '%' . $request->param('systemCode') . '%'];
            }

            // 排序
            $order = [];
            if (in_array($sortField, ['sort', 'create_time'])) {
                $order[$sortField] = $sortOrder == 'desc' ? 'desc' : 'asc';
            } else {
                $order['sort'] = 'asc';
            }

            // 查询数据
            $list = $this->model
                ->where($where)->where("is_deleted=0")
                ->order($order)
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);

            return json([
                'code' => 200,
                'message' => 'success',
                'order'=>$order,
                'data' => [
                    'list' => $list->items(),
                    'total' => $list->total(),
                    'current_page' => $list->currentPage(),
                    'last_page' => $list->lastPage(),
                    'per_page' => $list->listRows()
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 创建系统
     */
    public function create(Request $request)
    {
        try {
            $data = $request->param();

            // 验证数据
            $validate = Validate::make($this->model->rules, $this->model->message);
            if (!$validate->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ]);
            }

            // 检查系统编码是否已存在
            $exists = $this->model->where('system_code', $data['system_code'])->find();
            if ($exists) {
                return json([
                    'code' => 400,
                    'message' => '系统编码已存在'
                ]);
            }

            // 创建数据
            $result = $this->model->create([
                'system_code' => $data['system_code'],
                'system_name' => $data['system_name'],
                'system_tag' => $data['system_tag'],
                'sort' => intval($data['sort']),
                'icon' => $data['icon'] ?? '',
                'is_external' => $data['is_external'],
                'display_status' => $data['display_status'],
                'remark' => $data['remark'] ?? '',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ]);

            $help = new Help();
            $help->system_log($data, '创建系统');

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '创建成功',
                    'data' => $result
                ]);
            } else {
                return json([
                    'code' => 500,
                    'message' => '创建失败'
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新系统
     */
    public function update(Request $request)
    {
        $id = input("id") ?? '';
        try {
            $data = $request->param();

            // 检查记录是否存在
            $system = $this->model->find($id);
            if (!$system) {
                return json([
                    'code' => 404,
                    'message' => '系统不存在'
                ]);
            }

            // 验证数据（排除系统编码的必填验证）
            $rules = $this->model->rules;
            unset($rules['system_code']);

            $validate = Validate::make($rules, $this->model->message);
            if (!$validate->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ]);
            }

            // 更新数据
            $updateData = [
                'system_name' => $data['system_name'],
                'system_tag' => $data['system_tag'],
                'sort' => intval($data['sort']),
                'is_external' => $data['is_external'],
                'display_status' => $data['display_status'],
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ];

            // 如果有图标则更新图标
            if (isset($data['icon'])) {
                $updateData['icon'] = $data['icon'];
            }

            $result = $system->save($updateData);

            $help = new Help();
            $help->system_log($data, '修改系统');

            if ($result !== false) {
                return json([
                    'code' => 200,
                    'message' => '更新成功',
                    'data' => $system
                ]);
            } else {
                return json([
                    'code' => 500,
                    'message' => '更新失败'
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除系统
     */
    public function delete()
    {
        $id = input("id") ?? '';
        try {
            $system = $this->model->find($id);
            if (!$system) {
                return json([
                    'code' => 404,
                    'message' => '系统不存在'
                ]);
            }

            $result = $system->save(['is_deleted'=>1]);

            $help = new Help();
            $help->system_log($id, '删除系统');

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '删除成功'
                ]);
            } else {
                return json([
                    'code' => 500,
                    'message' => '删除失败'
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取单个系统详情
     */
    public function read()
    {
        $id = input("id") ?? '';
        try {
            $system = $this->model->find($id);
            if (!$system) {
                return json([
                    'code' => 404,
                    'message' => '系统不存在'
                ]);
            }

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $system
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }


}